<template>
	<view class="container">
		<!-- 导航栏 -->
		<view class="nav-bar">
			<view class="nav-left" @tap="goBack">
				<uni-icons type="left" size="20" color="#333"></uni-icons>
				<text class="nav-back-text">返回</text>
			</view>
			<text class="nav-title">消息详情</text>
			<view class="nav-right">
				<uni-icons type="more" size="20" color="#333" @tap="showMoreOptions"></uni-icons>
			</view>
		</view>

		<!-- 消息详情内容 -->
		<view class="message-detail" v-if="messageInfo">
			<!-- 发送者信息 -->
			<view class="sender-info">
				<view class="sender-avatar">
					<text class="avatar-text">{{ getSenderAvatarText() }}</text>
				</view>
				<view class="sender-details">
					<text class="sender-name">{{ messageInfo.title || '未知发送者' }}</text>
					<text class="send-time">{{ formatDetailTime(messageInfo.time) }}</text>
				</view>
				<view class="message-status" :class="getStatusClass()">
					<text class="status-text">{{ getStatusText() }}</text>
				</view>
			</view>

			<!-- 消息内容 -->
			<view class="message-content">
				<text class="content-text">{{ messageInfo.preview || messageInfo.content || '暂无内容' }}</text>
			</view>

			<!-- 消息操作 -->
			<view class="message-actions">
				<button class="action-btn reply-btn" @tap="replyMessage">
					<uni-icons type="chat" size="16" color="#fff"></uni-icons>
					<text>回复</text>
				</button>
				<button class="action-btn forward-btn" @tap="forwardMessage">
					<uni-icons type="forward" size="16" color="#666"></uni-icons>
					<text>转发</text>
				</button>
				<button class="action-btn mark-btn" @tap="markAsRead" v-if="!messageInfo.isRead">
					<uni-icons type="checkmarkempty" size="16" color="#666"></uni-icons>
					<text>标记已读</text>
				</button>
			</view>

			<!-- 相关信息 -->
			<view class="related-info" v-if="messageInfo.type === 'homework'">
				<view class="info-title">
					<uni-icons type="info" size="16" color="#1976D2"></uni-icons>
					<text>相关信息</text>
				</view>
				<view class="info-item" v-if="messageInfo.deadline">
					<text class="info-label">截止时间：</text>
					<text class="info-value">{{ messageInfo.deadline }}</text>
				</view>
				<view class="info-item" v-if="messageInfo.subject">
					<text class="info-label">科目：</text>
					<text class="info-value">{{ messageInfo.subject }}</text>
				</view>
			</view>

			<!-- 消息历史 -->
			<view class="message-history" v-if="relatedMessages.length > 0">
				<view class="history-title">
					<text>相关消息</text>
				</view>
				<view class="history-list">
					<view 
						v-for="msg in relatedMessages" 
						:key="msg.id" 
						class="history-item"
						@tap="loadMessage(msg)"
					>
						<view class="history-avatar">
							<text class="history-avatar-text">{{ msg.title.charAt(0) }}</text>
						</view>
						<view class="history-content">
							<text class="history-sender">{{ msg.title }}</text>
							<text class="history-preview">{{ msg.preview }}</text>
							<text class="history-time">{{ msg.time }}</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 加载状态 -->
		<view class="loading" v-else>
			<uni-icons type="spinner-cycle" size="30" color="#999"></uni-icons>
			<text class="loading-text">加载中...</text>
		</view>

		<!-- 更多操作菜单 -->
		<view v-if="showMoreMenu" class="more-menu-overlay" @tap="hideMoreOptions">
			<view class="more-menu" @tap.stop>
				<view class="menu-item" @tap="deleteMessage">
					<uni-icons type="trash" size="16" color="#ff4757"></uni-icons>
					<text class="menu-text">删除消息</text>
				</view>
				<view class="menu-item" @tap="reportMessage">
					<uni-icons type="flag" size="16" color="#ffa502"></uni-icons>
					<text class="menu-text">举报消息</text>
				</view>
				<view class="menu-item" @tap="hideMoreOptions">
					<uni-icons type="close" size="16" color="#666"></uni-icons>
					<text class="menu-text">取消</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { ref, onMounted } from 'vue';

	interface MessageInfo {
		id: string;
		title: string;
		time: string;
		preview: string;
		content?: string;
		isRead: boolean;
		type?: string;
		deadline?: string;
		subject?: string;
		fromUser?: string;
	}

	// 消息信息
	const messageInfo = ref<MessageInfo | null>(null);
	const relatedMessages = ref<MessageInfo[]>([]);
	const showMoreMenu = ref(false);

	// 页面加载时获取消息详情
	onMounted(() => {
		const pages = getCurrentPages();
		const currentPage = pages[pages.length - 1];
		const options = currentPage.options;
		
		console.log('📱 消息详情页面加载，参数:', options);
		
		if (options.messageId) {
			loadMessageDetail(options.messageId);
		} else if (options.messageData) {
			// 直接传递的消息数据
			try {
				messageInfo.value = JSON.parse(decodeURIComponent(options.messageData));
				loadRelatedMessages();
			} catch (e) {
				console.error('消息数据解析失败:', e);
				showErrorAndGoBack();
			}
		} else {
			showErrorAndGoBack();
		}
	});

	// 加载消息详情
	const loadMessageDetail = (messageId: string) => {
		console.log('📬 加载消息详情, ID:', messageId);
		
		// 先从本地存储的消息列表中查找
		const savedMessages = uni.getStorageSync('messageList') || [];
		const foundMessage = savedMessages.find((msg: MessageInfo) => msg.id === messageId);
		
		if (foundMessage) {
			messageInfo.value = foundMessage;
			loadRelatedMessages();
		} else {
			// 如果本地没有，可以从服务器获取
			// 这里暂时使用演示数据
			loadDemoMessage(messageId);
		}
	};

	// 加载演示消息
	const loadDemoMessage = (messageId: string) => {
		const demoMessages = {
			'demo_system': {
				id: 'demo_system',
				title: '系统通知',
				time: '刚刚',
				preview: '欢迎使用EduLiveLink教育平台！',
				content: '尊敬的用户，欢迎您使用EduLiveLink智能教育平台！\n\n我们为您提供了丰富的学习功能：\n• 在线课程学习\n• 作业提交与批改\n• 实时消息通知\n• 学习进度跟踪\n\n如有任何问题，请随时联系客服。祝您学习愉快！',
				isRead: false,
				type: 'system'
			},
			'demo_teacher': {
				id: 'demo_teacher',
				title: '张教授',
				time: '10分钟前',
				preview: '请注意：明天上午9点有重要的数学测验，请准时参加',
				content: '各位同学：\n\n明天（9月12日）上午9:00-11:00将进行高等数学期中测验。\n\n考试内容：\n• 第一章：函数与极限\n• 第二章：导数与微分\n• 第三章：积分学基础\n\n考试地点：教学楼A座201教室\n请同学们准时参加，携带学生证和文具。\n\n祝大家考试顺利！',
				isRead: false,
				type: 'homework',
				deadline: '2024-09-12 09:00',
				subject: '高等数学'
			},
			'demo_homework': {
				id: 'demo_homework',
				title: '作业提醒',
				time: '1小时前',
				preview: '您有3项作业即将到期，请及时完成并提交',
				content: '以下作业即将到期，请及时完成：\n\n1. 高等数学作业（第三章习题）\n   截止时间：2024-09-12 23:59\n   \n2. 英语口语练习\n   截止时间：2024-09-13 18:00\n   \n3. 物理实验报告\n   截止时间：2024-09-14 12:00\n\n请登录系统完成并提交作业。',
				isRead: false,
				type: 'homework'
			}
		};
		
		messageInfo.value = demoMessages[messageId] || demoMessages['demo_system'];
		loadRelatedMessages();
	};

	// 加载相关消息
	const loadRelatedMessages = () => {
		// 这里可以根据消息类型、发送者等加载相关消息
		// 暂时使用演示数据
		relatedMessages.value = [
			{
				id: 'related_1',
				title: '张教授',
				time: '昨天',
				preview: '下周的实验课程安排已更新',
				isRead: true
			},
			{
				id: 'related_2',
				title: '系统通知',
				time: '2天前',
				preview: '系统维护通知',
				isRead: true
			}
		];
	};

	// 返回上一页
	const goBack = () => {
		uni.navigateBack();
	};

	// 显示错误并返回
	const showErrorAndGoBack = () => {
		uni.showToast({
			title: '消息不存在',
			icon: 'none'
		});
		setTimeout(() => {
			uni.navigateBack();
		}, 1500);
	};

	// 获取发送者头像文字
	const getSenderAvatarText = () => {
		return messageInfo.value?.title.charAt(0) || '消';
	};

	// 格式化详细时间
	const formatDetailTime = (timeString: string) => {
		if (!timeString) return '';
		if (timeString === '刚刚') return new Date().toLocaleString('zh-CN');
		if (timeString.includes('分钟前')) {
			const minutes = parseInt(timeString);
			const time = new Date(Date.now() - minutes * 60000);
			return time.toLocaleString('zh-CN');
		}
		if (timeString.includes('小时前')) {
			const hours = parseInt(timeString);
			const time = new Date(Date.now() - hours * 3600000);
			return time.toLocaleString('zh-CN');
		}
		return timeString;
	};

	// 获取状态样式
	const getStatusClass = () => {
		return messageInfo.value?.isRead ? 'read' : 'unread';
	};

	// 获取状态文字
	const getStatusText = () => {
		return messageInfo.value?.isRead ? '已读' : '未读';
	};

	// 回复消息
	const replyMessage = () => {
		uni.showModal({
			title: '回复消息',
			content: '回复功能正在开发中，敬请期待！',
			showCancel: false
		});
	};

	// 转发消息
	const forwardMessage = () => {
		uni.showActionSheet({
			itemList: ['转发给朋友', '分享到班级群', '复制消息内容'],
			success: (res) => {
				const actions = ['转发给朋友', '分享到班级群', '复制消息内容'];
				uni.showToast({
					title: `${actions[res.tapIndex]}功能开发中`,
					icon: 'none'
				});
			}
		});
	};

	// 标记已读
	const markAsRead = () => {
		if (messageInfo.value) {
			messageInfo.value.isRead = true;
			
			// 更新本地存储
			const savedMessages = uni.getStorageSync('messageList') || [];
			const index = savedMessages.findIndex((msg: MessageInfo) => msg.id === messageInfo.value?.id);
			if (index !== -1) {
				savedMessages[index].isRead = true;
				uni.setStorageSync('messageList', savedMessages);
			}
			
			uni.showToast({
				title: '已标记为已读',
				icon: 'success'
			});
		}
	};

	// 显示更多选项
	const showMoreOptions = () => {
		showMoreMenu.value = true;
	};

	// 隐藏更多选项
	const hideMoreOptions = () => {
		showMoreMenu.value = false;
	};

	// 删除消息
	const deleteMessage = () => {
		uni.showModal({
			title: '确认删除',
			content: '确定要删除这条消息吗？',
			success: (res) => {
				if (res.confirm) {
					// 删除逻辑
					uni.showToast({
						title: '消息已删除',
						icon: 'success'
					});
					setTimeout(() => {
						uni.navigateBack();
					}, 1000);
				}
			}
		});
		hideMoreOptions();
	};

	// 举报消息
	const reportMessage = () => {
		uni.showToast({
			title: '举报功能开发中',
			icon: 'none'
		});
		hideMoreOptions();
	};

	// 加载指定消息
	const loadMessage = (msg: MessageInfo) => {
		messageInfo.value = msg;
		loadRelatedMessages();
	};
</script>

<style scoped>
	.container {
		min-height: 100vh;
		background: #f5f5f5;
	}

	/* 导航栏 */
	.nav-bar {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 10rpx 30rpx;
		background: #fff;
		border-bottom: 1rpx solid #e0e0e0;
		position: sticky;
		top: 0;
		z-index: 100;
	}

	.nav-left {
		display: flex;
		align-items: center;
		gap: 10rpx;
	}

	.nav-back-text {
		font-size: 28rpx;
		color: #333;
	}

	.nav-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
	}

	.nav-right {
		width: 60rpx;
		display: flex;
		justify-content: flex-end;
	}

	/* 消息详情 */
	.message-detail {
		padding: 40rpx 30rpx;
	}

	.sender-info {
		display: flex;
		align-items: center;
		background: #fff;
		padding: 30rpx;
		border-radius: 16rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
	}

	.sender-avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 24rpx;
	}

	.avatar-text {
		color: white;
		font-size: 32rpx;
		font-weight: bold;
	}

	.sender-details {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 8rpx;
	}

	.sender-name {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
	}

	.send-time {
		font-size: 24rpx;
		color: #999;
	}

	.message-status {
		padding: 6rpx 16rpx;
		border-radius: 12rpx;
		font-size: 22rpx;
	}

	.message-status.read {
		background: #e8f5e8;
		color: #4CAF50;
	}

	.message-status.unread {
		background: #fff3e0;
		color: #ff9800;
	}

	/* 消息内容 */
	.message-content {
		background: #fff;
		padding: 40rpx 30rpx;
		border-radius: 16rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
	}

	.content-text {
		font-size: 28rpx;
		line-height: 1.6;
		color: #333;
		white-space: pre-line;
	}

	/* 消息操作 */
	.message-actions {
		display: flex;
		gap: 20rpx;
		margin-bottom: 30rpx;
	}

	.action-btn {
		flex: 1;
		height: 80rpx;
		border-radius: 12rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 10rpx;
		font-size: 26rpx;
		border: none;
	}

	.reply-btn {
		background: #1976D2;
		color: white;
	}

	.forward-btn, .mark-btn {
		background: #f5f5f5;
		color: #666;
	}

	/* 相关信息 */
	.related-info {
		background: #fff;
		padding: 30rpx;
		border-radius: 16rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
	}

	.info-title {
		display: flex;
		align-items: center;
		gap: 10rpx;
		margin-bottom: 20rpx;
		font-size: 28rpx;
		font-weight: 600;
		color: #333;
	}

	.info-item {
		display: flex;
		margin-bottom: 16rpx;
		font-size: 26rpx;
	}

	.info-label {
		color: #666;
		margin-right: 10rpx;
	}

	.info-value {
		color: #333;
		font-weight: 500;
	}

	/* 消息历史 */
	.message-history {
		background: #fff;
		border-radius: 16rpx;
		padding: 30rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
	}

	.history-title {
		font-size: 28rpx;
		font-weight: 600;
		color: #333;
		margin-bottom: 24rpx;
	}

	.history-item {
		display: flex;
		align-items: center;
		padding: 20rpx;
		margin-bottom: 16rpx;
		background: #f8f9fa;
		border-radius: 12rpx;
	}

	.history-avatar {
		width: 50rpx;
		height: 50rpx;
		border-radius: 50%;
		background: linear-gradient(135deg, #a8e6cf 0%, #88d8a3 100%);
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 16rpx;
	}

	.history-avatar-text {
		color: white;
		font-size: 20rpx;
		font-weight: bold;
	}

	.history-content {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 4rpx;
	}

	.history-sender {
		font-size: 24rpx;
		font-weight: 500;
		color: #333;
	}

	.history-preview {
		font-size: 22rpx;
		color: #666;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.history-time {
		font-size: 20rpx;
		color: #999;
	}

	/* 加载状态 */
	.loading {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100rpx;
		gap: 20rpx;
	}

	.loading-text {
		font-size: 26rpx;
		color: #999;
	}

	/* 更多操作菜单 */
	.more-menu-overlay {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		z-index: 999;
		display: flex;
		align-items: flex-end;
	}

	.more-menu {
		width: 100%;
		background: #fff;
		border-radius: 24rpx 24rpx 0 0;
		padding: 30rpx;
	}

	.menu-item {
		display: flex;
		align-items: center;
		gap: 20rpx;
		padding: 24rpx 20rpx;
		border-radius: 12rpx;
		margin-bottom: 16rpx;
		font-size: 28rpx;
	}

	.menu-item:hover {
		background: #f5f5f5;
	}

	.menu-text {
		color: #333;
	}
</style>



















